package cae.logic.emo;

import java.awt.Image;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

import org.apache.log4j.Logger;

import cae.logic.util.CaeSplitter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class CaeEmoticonsManager {

	private static final String FILE = "emoticons.xml";
	private static Logger logger = Logger.getLogger(CaeEmoticonsManager.class);
	private static CaeEmoticonsManager instance;
	private Map<String, CaeEmoticonDefinition> defsMap;
	private CaeSplitter splitter;
	private static XStream xstream = new XStream(new DomDriver());
	private List<CaeEmoticonDefinition> defs;

	@SuppressWarnings("unchecked")
	private CaeEmoticonsManager()
	{
		try 
		{
			xstream.alias("emoticon", CaeEmoticonDefinition.class);
			defsMap = new HashMap<String, CaeEmoticonDefinition>();
			StringBuilder splitterPatternStringB = new StringBuilder();
			
			InputStream file = new FileInputStream(FILE); 
			defs = (List<CaeEmoticonDefinition>) xstream.fromXML(file);
			
			for (CaeEmoticonDefinition definition : defs) 
			{
				String[] keysSet = definition.getKeySets();
				for (String keyset : keysSet) {
					defsMap.put(keyset, definition);
					splitterPatternStringB.append("\\Q"+keyset+"\\E"+"|");
				}
			}

			String splitterPatternString = splitterPatternStringB.substring(0, splitterPatternStringB.length()-1);

			Pattern pattern = Pattern.compile(splitterPatternString);
			splitter = new CaeSplitter(pattern, true);

			file.close();
		}
		catch (Exception e) {
			logger.fatal("Error al leer el archivo de emoticons ", e);
			throw new RuntimeException("Error al leer el archivo de emoticons ", e);
		}
	}

	public static CaeEmoticonsManager getInstance()
	{
		if(instance == null)
			instance = new CaeEmoticonsManager();
		return instance;
	}

	public ImageIcon getEmoticonImg(CaeEmoticonDefinition key)
	{
		ImageIcon i = new ImageIcon("img/emo/"+key.getImgPath(), key.getName());
		return i;
	}
	
	public Image getEmoticonImage(CaeEmoticonDefinition key)
	{
		Image i = new ImageIcon("img/emo/"+key.getImgPath(), key.getName()).getImage();
		return i;
	}

	public String[] splitText(String text)
	{
		return splitter.split(text);
	}
	
	public CaeEmoticonDefinition getEmoticon(String key)
	{
		return defsMap.get(key);
	}

	public void addStylesToDocument(StyledDocument doc)
	{
		Style def = StyleContext.getDefaultStyleContext().
		getStyle(StyleContext.DEFAULT_STYLE);

		Style regular = doc.addStyle("regular", def);
		StyleConstants.setFontFamily(def, "SansSerif");

		Style s = doc.addStyle("italic", regular);
		StyleConstants.setItalic(s, true);

		s = doc.addStyle("bold", regular);
		StyleConstants.setBold(s, true);

		s = doc.addStyle("small", regular);
		StyleConstants.setFontSize(s, 10);

		s = doc.addStyle("large", regular);
		StyleConstants.setFontSize(s, 16);

		// emos
		Set<String> emoKeys = defsMap.keySet();
		for (String emoKey: emoKeys) 
		{
			s = doc.addStyle(emoKey, regular);
			StyleConstants.setIcon(s, getEmoticonImg(defsMap.get(emoKey)));
		}
	}

	public List<CaeEmoticonDefinition> getEmoticons() {
		return defs;
	}
	
	

	/*public static void main(String[] argv) throws FileNotFoundException, IOException {


        //pattern = Pattern.compile(":D|\\Q:-(\\E|:p|\\Q(a)\\E|\\Q(*)\\E");


        String text = "Hola :-( como (*) estas :p todo (a) ok :D";
        int counter = 1;
        for (String part : splitter.split(text)) {
            System.out.printf("Part %d: \"%s\"\n", counter++, part);
        }
    }*/
	
	/*public static void main(String[] args) throws FileNotFoundException {
		
		Set<Object> emos = CaeEmoticonsManager.getInstance().getEmoticonsKeys();
		List<CaeEmoticonDefinition> defs = new ArrayList<CaeEmoticonDefinition>();
		for (Object object : emos) {
			
			String img = CaeEmoticonsManager.getInstance().p.getProperty((String)object);
			CaeEmoticonDefinition ddd = getByImg(img, defs);
			
			if(ddd == null)
			{
				String[] a = new String[1];
				a[0] = ((String)object).trim();
				CaeEmoticonDefinition dd = new CaeEmoticonDefinition(img.trim(), "name", a);
				defs.add(dd);
			}
			else
			{
				String[] aaa= ddd.getKeySets();
				String[] bbb = new String[aaa.length+1];
				for (int i = 0; i < aaa.length; i++) {
					String string = aaa[i];
					bbb[i] = string;
				}
				bbb[aaa.length]= ((String)object).trim();
				ddd.setKeySets(bbb);
			}
		}
		xstream.toXML(defs, new FileOutputStream("emoticons.xml"));
	}
	
	private static CaeEmoticonDefinition getByImg(String img, List<CaeEmoticonDefinition> defs)
	{
		for (CaeEmoticonDefinition definition : defs) {
			if(definition.getImgPath().equals(img))
				return definition;
		}
		return null;
	}*/
}
